package dtos

import (
	"github.com/edgexfoundry/edgex-go/internal/app/models"
	"github.com/edgexfoundry/go-mod-core-contracts/v2/dtos"
	dtoCommon "github.com/edgexfoundry/go-mod-core-contracts/v2/dtos/common"
	edgexModels "github.com/edgexfoundry/go-mod-core-contracts/v2/models"
)

type DeviceProfileAddRequest struct {
	dtoCommon.BaseRequest `json:",inline"`
	Profile               models.DeviceProfile `json:"profile"`
	DeviceId              string               `json:"deviceId"`
	ApiVersion            string               `json:"apiVersion"`
}

type DeviceProfile struct {
	dtos.DeviceProfile `json:",inline"`
	DeviceResources    []DeviceResource `json:"deviceResources"`
	DeviceCommands     []DeviceCommand  `json:"deviceCommands"`
}

func (d *DeviceProfile) ToDeviceProfileModel() models.DeviceProfile {
	return models.DeviceProfile{
		DeviceProfile: edgexModels.DeviceProfile{
			DBTimestamp:  edgexModels.DBTimestamp(d.DBTimestamp),
			Description:  d.Description,
			Id:           d.Id,
			Name:         d.Name,
			Manufacturer: d.Manufacturer,
			Model:        d.Model,
			Labels:       d.Labels,
		},
		DeviceResources: ToDeviceResources(d.DeviceResources),
		DeviceCommands:  ToDeviceCommandModels(d.DeviceCommands),
	}
}

func (d *DeviceProfile) FromAiotToEdgexDto() dtos.DeviceProfile {

	dp := d.DeviceProfile
	resources := make([]dtos.DeviceResource, len(d.DeviceResources))
	commands := make([]dtos.DeviceCommand, len(d.DeviceCommands))

	for index, resource := range d.DeviceResources {
		resources[index] = resource.DeviceResource
	}

	for index, command := range d.DeviceCommands {
		dc := command.DeviceCommand
		ros := make([]dtos.ResourceOperation, len(command.ResourceOperations))
		for i, operation := range command.ResourceOperations {
			ros[i] = operation.ResourceOperation
		}
		dc.ResourceOperations = ros
		commands[index] = dc
	}
	dp.DeviceResources = resources
	dp.DeviceCommands = commands
	return dp
}
